#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QHostAddress>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    server = new QTcpServer(this);
    bool r = server->listen(QHostAddress("127.0.0.1"), 6666);
    if(!r){
        server->close();
    }
    connect(server, SIGNAL(newConnection()), this, SLOT(slotNewConnection()));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::slotNewConnection()
{
    clientSocket = server->nextPendingConnection();
    connect(clientSocket, SIGNAL(readyRead()), this, SLOT(slotReadyRead()));
}

void MainWindow::slotReadyRead(){
    QByteArray bytes = clientSocket->readAll();
    QString message = QString::fromUtf8(bytes);
    if(message == QString::fromUtf8("你好")){
        clientSocket->write(QString("你好，客户端").toUtf8());
    }else if(message == QString::fromUtf8("天王盖地虎")){
        clientSocket->write(QString("宝塔镇河妖").toUtf8());
    }else if(message == QString::fromUtf8("xxx.txt")){
        clientSocket->write(QString("正在发送xxx.txt").toUtf8());
    }
}
